/**
 * Created by xu_jiaHui on 2017/3/30.
 */
var select;
var userMobile = ""
var faultType = [{"value": "0", "name": "正常"}, {"value": "1", "name": "膜脱落"}, {"value": "2", "name": "膜淡化"},
    {"value": "3", "name": "逆反射系数不达标"}, {"value": "4", "name": "卷边"}, {"value": "5", "name": "转向"},
    {"value": "6", "name": "非国际"}, {"value": "7", "name": "抱箍缺少"}, {"value": "8", "name": "净空高不达标"},
    {"value": "9", "name": "设置不合理"}, {"value": "10", "name": "缺失"}, {"value": "11", "name": "建议增设"},
    {"value": "12", "name": "与交通组织矛盾"}, {"value": "13", "name": "内容有误"}, {"value": "14", "name": "标牌与标杆不配套"},
    {"value": "15", "name": "非公指示牌"}];
$.getActorId = function (data) {
    var actorId = 0;
    if (data.indexOf("7") >= 0)
        actorId = 7;
    if (data.indexOf("3") >= 0)
        actorId = 3;
    if (data.indexOf("1") >= 0)
        actorId = 1;
    return actorId;
};


$.getOrgList = function () {
    var actorId = 7;
    if (gUserLoginResult.userActors.indexOf("1") >= 0)
        actorId = 1;
    $.ajax({
        url: "../rds_fault/getOrg4Select",
        type: "post",
        dataType: "json",
        async: false,
        data: {
            "actorId": actorId,
            "orgId": gUserLoginResult.orgId
        },
        success: function (msg) {
            if (msg != null || typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    select = "<select id='orgSelect' class='form-control' name='searchText'>" +
                        "<option val=''>全部维护单位</option>"
                    var orgData = msg.jsonData;
                    for (var i = 0; i < orgData.length; i++) {
                        var icon = "Ⅰ";
                        if (orgData[i].orgType == 0)
                            icon = "Ⅱ";
                        select += "<option val=" + orgData[i].orgId + ">" + icon + "&nbsp;" + orgData[i].orgName + "</option>";
                    }
                    select += "</select>";
                } else
                    $.alert("获取公司列表失败", 2);
            }
        }
    })
};

$.getOrgList();

var gActorId = $.getActorId(gUserLoginResult.userActors);
$(function () {
    gMainDT = $("#mainDataTables").DataTable({
        ajax: {
            url: "../rds_fault/getFault4DT",
            type: "POST",
            data: function (d) {
                d.search = $('#mainDataTables').DataTable().search(this.value);
                d.actorId = gActorId;
                d.gActorId = 7;
                d.userId = gUserLoginResult.userId;
                d.orgId = gUserLoginResult.orgId;
            }
        },
        columns: [{
            data: "signFaultId",
            targets: 0
        }, {
            data: "roadSignPic",
            render: function (data, type, row) {
                return "<img src='" + data + "'style='width:50px;height:40px;cursor: pointer' " +
                    "onclick='$.showPicModal(\"" + data + "\")'> ";
            }
        }, {
            data: "orgName"
        }, {
            data: "signFaultPeopleName"
        }, {
            data: "signCheckTime",
            render: function (data, type, row) {
                return data.substring(0, 10);
            }
        }, {
            data: "companyUserName"
        }, {
            data: "mainCheckName",
            render: function (data, type, row) {
                if (data == null) {
                    return "暂未审核"
                }
                else {
                    return data;
                }
            }
        }, {
            data: "roadSignId",
            render: function (data, type, row) {
                var allData = JSON.stringify(row).replace(/\'/g, "&apos;");
                return "<button class='btn btn-primary btn-xs btn-flat' onclick='$.signDetails (" + allData + ")' title='标牌详情'>点击查看</button>";
            }
        }, {
            data: "signFaultId",
            render: function (data, type, row) {
                var allData = JSON.stringify(row).replace(/\'/g, "&apos;");
                return checkButton = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.faultDetails (" + allData + ")' title='故障详情'>点击查看</button>";
            }
        }, {
            data: "signFaultId",
            render:function (data,type,row) {
                var allData = JSON.stringify(row).replace(/\'/g, "&apos;");
                return checkButton = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.faultInfoDetails (" + allData + ")' title='故障状态'>点击查看</button>";
            }

        },{
            data: "signFaultId",
            render: function (data, type, row) {
                // 左侧工具栏按钮的权限
                // var buttonInsert = "<button class='btn btn-info btn-xs btn-flat' onclick='$.addFaultReport()' title='添加'><i class='fa fa-plus-square'></i></button>";
                var buttonAudit = "";
                var allData = JSON.stringify(row).replace(/\'/g, "&apos;");
                if (gActorId == 7 || gActorId == 1 || gActorId == 3) {
                    if (row.mainCheck == 0)
                        buttonAudit = "<button  class='btn btn-primary btn-xs btn-flat'  onclick='$.showCheckModal(" + allData + ",7)'><span class='glyphicon glyphicon-check' aria-hidden='true' ></span>审核</button>";
                    if (row.mainCheck == -1)
                        buttonAudit = "<button  class='btn btn-primary btn-xs btn-flat' disabled='disabled'>未通过</button>";
                    if (row.mainCheck == 1)
                        buttonAudit = "<button  class='btn btn-primary btn-xs btn-flat' disabled='disabled'>已通过</button>";
                }
                return buttonAudit;
            }
        }],
        dom: "<'row'<'col-md-4'l><'#mainToolbar.col-md-8'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'><button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>";
            strToolBar += "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>";
            strToolBar += "<span class='caret'></span><span class='sr-only'>切换下拉</span></button><ul class='dropdown-menu'>";
            strToolBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-reFaultReportesh'></i> 刷新</button></li>";
            // var buttonInsert = "<li><button href='#' class='btn btn-info btn-sm btn-flat btn-block' onclick='$.addFaultReport()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            // 下拉工具栏不处理更新事件，但今后可能需要审核等功能，替换该位置即可
            //var buttonUpdate = "<li><button href='#' class='btn btn-warning btn-sm btn-flat btn-block' onclick='$.updateFaultReport()'><i class='fa fa-edit'></i> 编辑</button></li>";
            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.deleteFaultReport(0)'><i class='fa fa-minus-square'></i> 删除</button></li>";
            // gInsert == 0 ? strToolBar : strToolBar += buttonInsert;
            // 同上方更新事件同时处理
            //gUpdate == 0 ? strToolBar : strToolBar += buttonUpdate;
            // gDelete == 0 ? strToolBar : strToolBar += buttonDelete;
            strToolBar += "</ul></div> <div class='input-group input-group-sm'>" + select + "";
            strToolBar += "<span class='input-group-btn'><button class='btn btn-primary  btn-flat' type='button' onclick='$(this).searchDT()'><i class='fa fa-search'></i></button></span></div></div>";
            $("#mainToolbar").append(strToolBar);
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });
    //获取用户电话
    $.ajax({
        url: "../rds_user/getUserById",
        type: "POST",
        async: false,
        data: {
            userId: gUserLoginResult.userId
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess == true) {
                    userMobile = msg.jsonData.userMobile;
                } else {
                    $.alert("获取监管单位数据失败", 2);
                }
            }
        }
    });
    //故障类型初始化(上报时)
    var faultTypeInit = "";
    for (var i = 0; i < faultType.length; i++) {
        faultTypeInit += "<option value='" + faultType[i].value + "'>" + faultType[i].name + "</option>";
    }
    $("#addfault_signFaultType").append(faultTypeInit);
});
// 搜索框查询操作
$.fn.searchDT = function () {
    // 注意gSelect查询权限的处理，由该表是否存在添加人或者审核人决定
    var searchText = $("#orgSelect").find("option:selected").attr("val");
    gMainDT.search(searchText).draw();
};

$.faultDetails = function (data) {
    $("#addfault_signFaultPeopleName").text(data.signFaultPeopleName);
    $("#addfault_signFaultPeopleMobile").text(data.signFaultPeopleMobile);
    $("#addfault_roadName").text(data.roadName);
    $("#addfault_address").text(data.province + "" + data.city + "" + data.area + " " + data.roadName + " " + data.startRoad + "(起)--" + data.endRoad + "(止)");
    $("#addfault_signFaultPic").attr("src", data.roadSignPic);
    $("#addfault_repairAmount").val(data.repairAmount);
    $("#addfault_signFaultType").val(data.signFaultType);
    $("#addfault_signFaultLevel").val(data.signFaultLevel);
    $("#addfault_signFaultReason").val(data.signFaultReason);

    $("#addfault_repairAmount").attr("disabled",true);
    $("#addfault_signFaultType").attr("disabled",true);
    $("#addfault_signFaultLevel").attr("disabled",true);
    $("#addfault_signFaultReason").attr("disabled",true);
    $("#addfault_signBtn").attr("disabled",true);
    $("#reportBtn").hide();
    $("#addfault_signBtn").hide()
    $("#addfaultModalLabel").text("故障详情");
    $("#addfaultModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};
var ggJsonData;
$.showCheckModal = function (jsonData, actor) {
    ggactor = actor;
    ggJsonData = jsonData;
    MaintenancePeopleNames = "";
    $("#addPerson").hide();
    $.ajax({
        url: "../rds_fault/getlongLatitude4Map",
        type: "POST",
        dataType: "json",
        data: {
            "roadSignId": jsonData.roadSignId
        },
        success: function (jsonData) {
            var url = "fault/map.html";
            url += "?x=" + jsonData[0].longitude + "&y=" + jsonData[0].latitude + "";//通过这种方式传参数
            $("#showEventContent4Audit").attr("src", url);
        }
    });
    if (gActorId == 1 || gActorId == 7)
        $("#ac-button").show();
    else
        $("#ac-button").hide();
    $("#notac-button").show();
    $("#signFaultCheckBack4Audit").val(jsonData.signFaultCheckBack)
    $("#signFaultId").val(jsonData.signFaultId);
    $("#signFaultCheckBack4Audit").removeAttr("readOnly");
    $("#signFaultId4Audit").html(jsonData.signFaultId);
    var faultLevel;
    switch (jsonData.signFaultLevel) {
        case 1:
            faultLevel = "一级";
            break;
        case 2:
            faultLevel = "二级";
            break;
        case 3:
            faultLevel = "三级";
            break;
        case 4:
            faultLevel = "四级";
            break;
        case 5:
            faultLevel = "五级";
            break;
        default:
            faultLevel = "未知";
            break;
    }
    $("#signFaultLevel4Audit").html(faultLevel);
    $("#signFaultType4Audit").html(faultType[jsonData.signFaultType].name);
    $("#checkPerson4Audit").html(jsonData.mainCheckName);
    $("#signFaultPeopleName4Audit").html(jsonData.signFaultPeopleName);
    $("#signFaultTime4Audit").html(jsonData.signFaultTime.substring(0, 10));
    $("#signFaultReason4Audit").html(jsonData.signFaultReason);
    $("#checkPerson4Audit").html(jsonData.companyUserName);
    $("#signFaultPic4Audit").attr('src', jsonData.signFaultPic);
    $("#preViewImg").attr('src', jsonData.signFaultPic);
    $("#auditModalLabel").text("当前故障审核");
    $("#auditModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};
//通过审核按钮
$("#ac-button").click(function () {
    $.signFaultAudit(1, ggactor);
});
//拒绝审核按钮
$("#notac-button").click(function () {
    $.signFaultAudit(-1, ggactor);
});
$.getTime = function () {
    $.changeTimeType = function (date) {
        if (date >= 0 && date <= 9) {
            date = "0" + date;
        }
        return date;
    };
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = $.changeTimeType(date.getMonth() + 1);
    var strDate = $.changeTimeType(date.getDate());
    var hour = $.changeTimeType(date.getHours());
    var minutes = $.changeTimeType(date.getMinutes());
    var seconds = $.changeTimeType(date.getSeconds());

    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + hour + seperator2 + minutes
        + seperator2 + seconds;
    return currentdate;
};
//审核操作
$.signFaultAudit = function (ispass, actor) {
    var signFaultCheckBack = $("#signFaultCheckBack4Audit").val();
    if (ispass == -1 || actor == 7) MaintenancePeopleId = null;
    if (signFaultCheckBack == "" && ispass == -1) {
        $.alert('请填写故障反馈', 2);
    } else if (signFaultCheckBack.length > 200) {
        $.alert("故障反馈字数不能超过200", 2);
    }  else {
        $.ajax({
            url: "../rds_fault/signFaultAudit",
            type: 'post',
            async: false,
            data: {
                userDevice: 'web',
                isPass: ispass,
                signFaultCheckBack: signFaultCheckBack,
                signFaultId: $("#signFaultId").val(),
                actorId: 7,
                signCheckTime: $.getTime(),
                maintenancePeopleId: ggJsonData.maintenancePeopleId,
                userId: gUserLoginResult.userId,
                "roadSignId": ggJsonData.roadSignId,
                "signFaultReason": ggJsonData.signFaultReason,
                "signFaultLevel": ggJsonData.signFaultLevel,
                "signFaultType": ggJsonData.signFaultType,
                "signFaultPic": ggJsonData.signFaultPic,
                "signFaultTime": $.getTime(),
                "repairAmount":ggJsonData.repairAmount
            },
            dataType: 'json',
            success: function (msg) {
                if (msg != null && typeof (msg) != "undefined") {
                    if (msg.isSuccess == true) {
                        $.alert("操作成功", 1);
                        $.closeShowModal();
                        MaintenancePeopleId = null;
                        gMainDT.ajax.reload(null, false);
                    } else
                        $.alert("操作失败！", 2);
                } else {
                    $.alert('系统错误', 2);
                }
            },
            error: function (data) {
                $.alert("系统错误", 2);
            }
        })
    }
};
$.showMePhoto = function () {
    if ($("#preViewImg").attr("src") != "") {
        $("#auditModal").modal("hide");
        $("#preModal").modal({
            backdrop: 'static',
            keyboard: false,
            show: true
        });
    } else {
        $.alert("未上传故障图片", 3);
    }

};
$.closePhoto = function () {
    $("#preModal").modal("hide");
    $("#auditModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

// 关闭showInfoModal
$.closeShowModal = function () {
    $("#auditModal").modal("hide");
    $("#signFaultCheckBack4Audit").val("");
    gMainDT.ajax.reload(null, false);
};

//标牌信息
$.signDetails = function (data) {
    $("#signProvince").val(data.province);
    $("#signCity").val(data.city);
    $("#signArea").val(data.area);
    $("#coordinate").val(data.longitude + "," + data.latitude);
    $("#signStartRoad").val(data.startRoad);
    $("#signEndRoad").val(data.endRoad);
    $("#signRoadName").val(data.roadName);
    if (data.roadSignPic != "" && data.roadSignPic != null) {
        $("#signRoadSignPic").attr("src", data.roadSignPic);
    }
    else {
        $("#signRoadSignPic").attr("src", "../images/default_photo.png");
    }
    $.ajax({
        url: "../rds_fault/getSignInfoBySignId",
        type: 'post',
        async: false,
        data: {
            userDevice: 'web',
            roadSignId: data.roadSignId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    $("#signCreateUserName").val(msg.jsonData.userName);
                    $("#signOrgName").val(msg.jsonData.orgName);
                    $("#signMainOrgName").val(msg.jsonData.mainOrgName);
                    $("#signEnvironment").val(msg.jsonData.environment);
                    $("#SignRoadSignType").val(msg.jsonData.roadSignType);
                    $("#signRoadSignInstallType").val(msg.jsonData.roadSignInstallType);
                    $("#signRoadSignShape").val(msg.jsonData.roadSignShape);
                    $("#roadSignInfoModalLabel").text("标牌信息");
                    $("#roadSignInfoModal").modal({
                        backdrop: 'static',
                        keyboard: false,
                        show: true
                    });
                } else
                    $.alert("修改失败！", 2);
            } else {
                $.alert('系统错误', 2);
            }
        },
        error: function (data) {
            $.alert("系统错误", 2);
        }
    });

};

$("#signRoadSignPic").click(function () {
    $.showPicModal($(this).attr("src"));
});

//地图
$.myBtnMap = function () {
    var coordinate = $("#coordinate").val().split(",");
    var url = "fault/roadPoleAuditMap.html";
    url += "?x=" + coordinate[0] + "&y=" + coordinate[1] + "&z=1";//通过这种方式传参数
    $("#myMap").attr("src", url);
    $("#modal-map").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
};

//故障状态
$.faultInfoDetails =function (data) {
    var status=-1;
    $(".ystep2").empty();
    $(".ystep2").loadStep({
        size: "large",
        color: "green",
        steps: [{
            title: "故障申报"
        },{
            title: "内部审核"
        },{
            title: "上报监管单位"
        },{
            title: "监管单位审核"
        },{
            title: "故障处理"
        },{
            title: "故障完成"
        }]
    });
    $.ajax({
        url: "../rds_fault/getSignFaultStatus",
        type: 'post',
        async: false,
        data: {
            userDevice: 'web',
            roadSignId: data.roadSignId,
            signFaultId: data.signFaultId
        },
        dataType: 'json',
        success: function (msg) {
            console.log(msg)
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    status=msg.jsonData;
                } else
                    $.alert("系统错误！", 2);
            } else {
                $.alert('系统错误', 2);
            }
        },
        error: function (data) {
            $.alert("系统错误", 2);
        }
    });

    $.ystepTest(status);
    $("#modal-signFaultStatus").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
}

// 关闭添加故障modal
$.closeAddfaultModal = function () {
    $("#addfault_signFaultLevel").val(1);
    $("#addfault_signFaultType").val(0);
    $("#addfault_signFaultPic").attr("src", "../images/default_photo.png");
    $("#addfault_roadName").html("");
    $("#addfault_address").html("");
    $("#addfault_repairAmount").val("");
    $("#addfault_signFaultReason").val("");

    $("#addfault_repairAmount").attr("disabled",false);
    $("#addfault_signFaultType").attr("disabled",false);
    $("#addfault_signFaultLevel").attr("disabled",false);
    $("#addfault_signFaultReason").attr("disabled",false);
    $("#addfault_signBtn").attr("disabled",false);

    $("#addfaultModal").modal("hide");
};
$.ystepTest =function (data) {
    switch (data){
        case 0://待内部审核
            $(".ystep2").setStep(2);
            break;
        case -1://内部拒绝
            $(".ystep2").setStep(2);
            $(".ystep-step-undone").css("color","red");
            break;
        case 2://待主管审核
            $(".ystep2").setStep(4);
            break;
        case -2://主管拒绝
            $(".ystep2").setStep(4);
            $(".ystep-step-undone").css("color","red");
            break;
        case 7://待维修
            $(".ystep2").setStep(5);
            break;
        case 8://维修中
            $(".ystep2").setStep(5);
            break;
        case 3://维修完成
            $(".ystep2").setStep(6);
            break;
        default:
            $(".ystep2").setStep(0);
            break;
    }
}